define(function(require, exports){
	var pubjs	= require('pubjs');
	var view	= require('@base/view');
	var util	= require('util');
	var $		= require('jquery');
	var Slave_Adx = pubjs.config('exchange_group/has_slave_qualification');
	var common	= require('modules/common');

	var SelectAptitude = view.container.extend({
		init: function(config, parent){
			config = pubjs.conf(config, {
				'class': 'P-infoAptitude',
				'view_model': {
					'select': this.eventSelect
					,'view': this.eventView
					,'remove': this.eventRemove
					,'error': ''
					,'status_maps': {
						'1': LANG('审核通过')
						,'-2': LANG('审核中')
						,'-1': LANG('审核未通过')
						,'0': LANG('待审核')
						,'empty': ''
						,'error': LANG('当前资质不包含该渠道')
					}
					,'defaultValue': {
						'valid': false,
						'label': '',
						'UserName': ''
					}
					,'aptitude': []
				}
			});

			this.$needAptitdueMap = pubjs.config('aptitude_group');
			this.Super('init', arguments);
		},
		afterBuild: function(){
			var self = this;
			var el = self.getContainer();

			el.append($([
				'<div class="P-infoSelectAptitudeBox">',
					'<span class="classify"> '+ LANG('选择默认资质，所有渠道资质与默认一致；如需单独设置某些渠道资质，请在下面选择；') +'</span>',
					'<br/>',
					'<span class="classify"> '+ LANG('（inmobi、亿告、玉米移动需要将资质关联BidEx渠道）') +'</span>',
					'<br/>',
					'<span class="classify"> '+ LANG('（搜狐移动需先关联搜狐渠道）') +'</span>',
					'<div class="content clear">',
						'<label class="default">',
							LANG('选择默认资质'),
							'<a ms-visible="!defaultValue.valid" ms-click="select(0)">'+ LANG('选择资质') +'</a>',
							'<a class="view" ms-attr-title="defaultValue.UserName" ms-visible="apti.valid" ms-click="view(0)">{{defaultValue.label}}</a>',
							'<i ms-click="remove(0)" ms-visible="defaultValue.valid" class="icon-close font-danger remove"></i>',
						'</label>',
						'<label class="labelItem" ms-repeat-apti="aptitude">',
							'{{apti.name}}',
							'<a ms-visible="!apti.valid" ms-click="select(apti.id)">'+ LANG('选择资质') +'</a>',
							'<a class="view" ms-attr-title="apti.UserName" ms-visible="apti.valid" ms-click="view(apti.aptiData._id)">{{apti.label}}</a>',
							'<i ms-click="remove(apti.id)" ms-visible="apti.valid" class="icon-close font-danger remove"></i>',
							'<em style="color:#aa0000">{{status_maps[apti.status]}}</em>',
						'</label>',
					'</div>',
				'</div>'
			].join('')));

			this.buildFromTemplate();
		},
		afterBuildTemplate: function(){
			var self	= this;
			var vm		= self.vm.$;
			var channels = pubjs.config('exchange');

			var data = [];
			util.each(channels, function(item) {
				if(item.hasAptitudes) {
					var v = util.clone(item);
					v.label = '';
					v.UserName = '';
					v.valid = false;
					v.status = 'empty';
					v.name = v.name + '：';
					data.push(v);
					//self.$needAptitudeAudit.push(v);
				}
			});

			vm.aptitude = data;
		},
		//移除已选资质
		eventRemove: function (id){
			var self = this
				, vm = self.vm.$
				, aptitude = id ? util.find(vm.aptitude, id,'id'): vm.defaultValue;

			aptitude.valid = false;
			aptitude.status = 'empty';
			aptitude.label = '';
			aptitude.UserName = '';
			aptitude.aptiData = null;
		},
		//弹出选择资质窗口
		eventSelect:function (id){
			var self = this;
			var dlg = self.get('selectAptitudeDlg');
			var param = {NoSlave: true};
			if(~Slave_Adx.indexOf(+id))
			{
				param.NoSlave = false;
			}

			if (!dlg)
			{
				this.createAsync('selectAptitudeDlg','addAccount/popwin/aptitude.selectAptitude',function(mod){
					mod.show(id).setParam(param).reload();
				});
			}
			else
			{
				dlg.show(id).setParam(param).reload();
			}
		},
		onSelectAptitude: function(ev){
			var self = this
				,data = ev.param.data
				,id = ev.param.id
				,aptitude
				,info
				,UserName
				,label;

			// 过滤历史脏数据，可能存在一个渠道可能存在多个记录
			data.Info = common.processQualificationInfo(data.Info);	

			if(id !== 0){
				aptitude = util.find(self.vm.$.aptitude, id,'id');
				if(aptitude && data){
					UserName = data.UserName;
					label = self.checkLabelLength(data.UserName);
					aptitude.UserName = UserName;
					aptitude.label = label;
					aptitude.valid = true;
					aptitude.aptiData = data;
					if(self.$needAptitdueMap.indexOf(id) > -1){
						info = util.find(data.Info, id, "ExchangeId");
						if(info){
							if(info.Status == -1){
								aptitude.valid = false;
							}
							else {
								aptitude.status = info.Status;
							}
						}
						else {
							aptitude.status = 'error';
							aptitude.valid	= false;
						}
					}
				}
			}
			// 如果选择的是默认资质，将其他资质都变成默认资质状态
			else if(id === 0){
				aptitude = self.vm.$.aptitude;
				var defu = self.vm.$.defaultValue;
				UserName = data.UserName;
				label = self.checkLabelLength(data.UserName);
				defu.UserName = UserName;
				defu.label = label;
				defu.valid = true;
				defu.aptiData = data;
				util.each(aptitude, function(item, idx){
					// 如果其他资质已选资质，不覆盖
					if(!item.valid){
						item.UserName = UserName;
						item.label = label;
						item.valid = true;
						item.aptiData = data;
						if(self.$needAptitdueMap.indexOf(item.id) > -1){
							info = util.find(data.Info, item.id, "ExchangeId");
							if(info){
								if(info.Status == -1){
									item.valid = false;
								}
								else {
									item.status	= info.Status;
								}
							}
							else {
								item.status	= 'error';
								item.valid	= false;
							}
						}
					}
				});
			}
		},
		//浏览已选资质详情
		eventView: function (id){
			var self	= this;
			var dlg		= self.get('viewAptitudeDlg');
			id = id || 0;
			if (!dlg){
				self.createAsync('viewAptitudeDlg', 'addAccount/popwin/aptitude.viewAptitude', function(mod){
					mod.load(id);
					mod.show();
				});
			}
			else {
				dlg.reset();
				dlg.load(id);
				dlg.show();
			}

			return false;
		},
		getData: function(){
			var self = this
				, aptitudes	= self.vm.$.aptitude
				, ret = [];

			util.each(aptitudes, function(item){
				if(item.valid){
					ret.push({
						'AdxId' : +item.id,
						'Aptitude' : item.UserName,
						'AptitudeId': ''+item.aptiData._id	//保存成字符串
					});
				}
			});

			return ret;
		},
		setData: function(data){
			var self = this,
				aptitudes = self.vm.$.aptitude;
			util.each(data, function(item){

				util.each(aptitudes, function(aptitude){
					if(item.AdxId == aptitude.id){
						aptitude.aptiData = {
							'_id' : +item.AptitudeId
						};
						var UserName = item.Aptitude;
						var label = self.checkLabelLength(item.Aptitude);
						aptitude.valid = true;
						aptitude.status = 'empty';
						aptitude.label = label;
						aptitude.UserName = UserName;
						return false;
					}
				})

			});
		},
		checkLabelLength: function(label){
			return label = label.length>12 ? label.substring(0,12)+'...' : label;
		}
	});

	exports.selectAptitude = SelectAptitude;
});